


async function gen_code(code){
    var getcode = layui.data("gen_code");
    if (getcode && getcode.code) {
        getcode = getcode + code;
    } else {
        getcode = code;
    }
    layui.data("gen_code",{
        key: "code",
        value: getcode
    });

}

async function fieldName(name){
    return await axios.get('/formData/getFieldName?name='+name)
        .then(function (response) {
            console.log("response",response);
            return response.data
        }).catch(function (error) {
            console.log("err",error);
            return null;
        }); 	
}


async function input(name, size, isRequired) {
    isRequired = isRequired?'required lay-verify="required" lay-reqtext="'+name+'不能为空"':'';
    var html = '  <div class="layui-form-item">\n' +
        '    <label class="layui-form-label" data-type="text">'+name+'</label>\n' +
        '    <div class="layui-input-'+size+'">\n' +
        '      <input type="text"  name="'+await fieldName(name)+'" '+isRequired+'  placeholder="请输入'+name+'内容" autocomplete="off" class="layui-input">\n' +
        '    </div>\n' +
        '  </div>\n';
    return html;
}
// 下拉框
async function select(name, size, isRequired, optList) {
    isRequired = isRequired?'required lay-verify="required" lay-reqtext="'+name+'不能为空"':'';
    var html = '  <div class="layui-form-item">\n' +
        '    <label class="layui-form-label" data-type="text">'+name+'</label>\n' +
        '    <div class="layui-input-'+size+'">\n' +
        '      <select name="'+await fieldName(name)+'" '+isRequired+'" lay-search>\n' +
        '        <option value=""></option>\n';
    
    for (var i=0; i < optList.length; ++i){
        html += '<option value="'+optList[i]+'">'+optList[i]+'</option>\n'
    }
    html +='      </select>\n    </div>\n  </div>\n';
    
    return html;
}

async function checkbox_many(name, size, optList) {
    
    var html = '  <div class="layui-form-item">\n' +
        '    <label class="layui-form-label" data-type="text">'+name+'</label>\n' +
        '    <div class="layui-input-'+size+'">\n';
    
    for (var i=0; i < optList.length; ++i) {
        html += '      <input type="checkbox" name="'+await fieldName(name)+'" title="'+optList[i]+'" value="'+optList[i]+'">\n';
    }

    html += '    </div>\n  </div>\n';
    return html;
}


async function checkbox_switch(name, isRequired, open_close_text) {
    isRequired = isRequired?'required lay-verify="required" lay-reqtext="'+name+'不能为空"':'';
    open_close_text = open_close_text?open_close_text:"打开|关闭"
    var html = '  <div class="layui-form-item">\n' +
        '    <label class="layui-form-label" data-type="text">'+name+'</label>\n' +
        '    <div class="layui-input-block">\n' +
        '      <input type="checkbox" name="'+await fieldName(name)+'" '+isRequired+'  class="switch_btn" value="yes" lay-skin="switch" lay-text="'+open_close_text+'" >\n' +
        '    </div>\n' +
        '  </div>\n';
    return html;
}
async function radio(name,size,optList) {
    // isRequired = isRequired?'required lay-verify="required" lay-reqtext="'+name+'不能为空"':'';
    var html = '  <div class="layui-form-item">\n' +
        '    <label class="layui-form-label" data-type="text">'+name+'</label>\n' +
        '    <div class="layui-input-'+size+'" >\n';
    // console.log("optList",optList);
    for (var i=0; i<optList.length; ++i){
        if (i===0) {
            html += '      <input type="radio" checked name="'+await fieldName(name)+'" value="'+optList[i]+'" title="'+optList[i]+'">\n';
        } else {
            html += '      <input type="radio" name="'+await fieldName(name)+'" value="'+optList[i]+'" title="'+optList[i]+'">\n';
        }
    }

    html += '    </div>\n  </div>\n';
    return html;
}

async function textarea(name,size, isRequired, placeholder) {
    isRequired = isRequired?'required lay-verify="required" lay-reqtext="'+name+'不能为空"':'';
    placeholder = placeholder?placeholder:"请输入文本";
    var html = '  <div class="layui-form-item layui-form-text">\n' +
        '    <label class="layui-form-label" data-type="text">'+name+'</label>\n' +
        '    <div class="layui-input-'+size+'">\n' +
        '      <textarea '+isRequired+' name="'+await fieldName(name)+'" placeholder="'+placeholder+'" class="layui-textarea"></textarea>\n' +
        '    </div>\n' +
        '  </div>\n';
    return html;
}
async function upload_file(name, tableID, accept){
    var fName = await fieldName(name)
    var html = `<div class="layui-form-item layui-form-text">
        <label class="layui-form-label upload" data-type="upload">`+name+`</label>
        <div class="layui-input-inline">
            <button type="button" class="layui-btn formPostFile" id="`+fName+`" name="`+fName+`" m_tableID=`+tableID+` m_accept="`+accept+`">
                <i class="layui-icon">&#xe67c;</i>上传文件
            </button>
        </div>
    </div>`
    return html
}

async function submits() {
    var html = '  <div class="layui-form-item">\n' +
        '    <div class="layui-input-block">\n' +
        '      <button class="layui-btn" id="formSubmit" lay-submit lay-filter="formCreated">立即提交</button>\n' +
        '      <button type="reset" class="layui-btn layui-btn-primary">重置</button>\n' +
        '    </div>\n' +
        '  </div>\n';
    return html;
}
function jscode() {

    var html = `
    layui.use(['form','tableSelect','upload'], async function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.jquery;
        var tableSelect = layui.tableSelect;
        var upload = layui.upload;


        // get stuID
        function get_stuID(){
        console.log('click');
                axios.post('/formData/getStuID')
                    .then(function (response) {
                    var data = response.data;
                    var seleStu = $('#stuID');
                    var ele;
                    for (var i=0; i<data.length; ++i){
                        ele = document.createElement('option');
                        ele.value = data[i];
                        ele.text = String(data[i]);
                        seleStu.append(ele);
                        }
                    form.render();
                    console.log(response)
                    }).catch(function (error) {
                        layer.msg("无法获取stuID",{icon:2})
                    }); 			
            };
        
        get_stuID();
        //监听提交
        form.on('submit(formCreated)', function (data) {
            var index = layer.alert(JSON.stringify(data.field), {
                title: '确认提交'
            }, function () {

                // 关闭弹出层
                layer.close(index);


                axios.post('/formData/formTablePost', data.field)
                .then(function (response) {
                    // console.log(response);
                    layer.msg("提交成功!",{icon:1});
                })
                .catch(function (error) {
                    layer.msg("提交失败!",{icon:2});

                }); 			

                
            });
            return false;
        });
        // 文件上传
        var uploadInst = upload.render({
            elem: '.upload' //绑定元素
            ,url: '/formData/formUploadFile' //上传接口
            ,done: function(res){
              //上传完毕回调
            }
            ,error: function(){
              //请求异常回调
            }
          });
    });`
    return html;
}



layui.define(['layer', 'form'], function(exports){
    var layer = layui.layer,
    form = layui.form,
    $ = layui.$;
    var count=0;


    async function gen_item_html(title, content_path, func){
        layer.open({
            title: title,
            type: 2,
            shade: 0.2,
            maxmin:true,
            shadeClose: true,
            // anim: 4,
            area: ['50%', '50%'],
            content: content_path,
            end:async function(){
                var carry_data = layui.data("form_data").carry
                layui.data("form_data",{
                    key:"carry",
                    value: ""
                });
                if (!carry_data.name) return false;
                html = await func(carry_data)
                console.log("carry_data",carry_data, carry_data.name);
                // html = input(carry_data.name, "field"+count,carry_data.size, carry_data.isRequired);
                console.log("html in end", html);
                // html = '<div class="layui-inline" id="'+"field"+count+'">'+html+'<button class="layui-btn layui-btn-sm layui-btn-danger del-form" data-type="del_each" id="'+"field_btn_"+count+'"> <i class="layui-icon">&#xe640;</i></button></div>'
                html = '<div class="layui-row" id="'+"field"+count+'"><div class="layui-col-md10">'+html+'</div><div class="layui-col-md1 layui-col-md-offset1"><button class="layui-btn  layui-btn-sm  layui-btn-primary layui-border-red"  data-type="del_each" id="'+"field_btn_"+count+'"> <i class="layui-icon">&#xe67e;</i></button></div></div>'
                $('form').append(html);
                form.render();
                $('#field_btn_'+count).on('click', function(){
                    this.parentElement.parentElement.outerHTML="";
                });
                ++count;
            }
        });
    }


    $('button').on('click',async function(){
        var _this = $(this),
        // size = _this.data('size'),
        type = _this.data('type'),
        html =  '';
        console.log("this", this);
        // console.log("_this", _this);
        
        switch (type) {
            case 'text':
                await gen_item_html('创建输入框','page/gen_form/gen_input.html', async function(carry_data){
                    return await input(carry_data.name, carry_data.size, carry_data.isRequired);
                })
                break;
            case 'select':
                await gen_item_html('创建下拉选择框','page/gen_form/gen_select.html', async function(carry_data){
                    var optList = Object.assign({}, carry_data);
                    delete optList.name;delete optList.size;delete optList.isRequired;
                    return await select(carry_data.name, carry_data.size, carry_data.isRequired, Object.values(optList));
                })
                break;
            case 'checkbox_many':
                    // html = checkbox_a(size)
                    await gen_item_html('创建复选框','page/gen_form/gen_check_many.html', async function(carry_data){
                        var optList = Object.assign({}, carry_data);
                        delete optList.name;delete optList.size;delete optList.isRequired;
                        return await checkbox_many(carry_data.name, carry_data.size, Object.values(optList));
                    })
                    
                    break;
            case 'checkbox_switch':
                await gen_item_html('创建开关','page/gen_form/gen_switch.html', async function(carry_data){
                    return await checkbox_switch(carry_data.name, carry_data.isRequired, carry_data.switch_open+'|'+carry_data.switch_close);
                })
                break;
            case 'radio':
                await gen_item_html('创建单选框','page/gen_form/gen_radio.html', async function(carry_data){
                    var optList = Object.assign({}, carry_data);
                    delete optList.name;delete optList.size;delete optList.isRequired;
                    return await radio(carry_data.name, carry_data.size, Object.values(optList));
                })
                break;
            case 'textarea':
                await gen_item_html('创建文本域','page/gen_form/gen_textarea.html', async function(carry_data){
                    return await textarea(carry_data.name, carry_data.size,carry_data.isRequired, carry_data.placeholder);
                })
                break;
            case 'upload_file':
                await gen_item_html('创建文件上传','page/gen_form/gen_upload_file.html', async function(carry_data){
                    return await upload_file(carry_data.name, "{tableID}", carry_data.accept);
                })
                break;
            case 'submit':
                html = await submits();
                html = '<div class="layui-row" id="'+"field"+count+'"><div class="layui-col-md10">'+html+'</div><div class="layui-col-md1 layui-col-md-offset1"><button class="layui-btn  layui-btn-sm  layui-btn-primary layui-border-red"  data-type="del_each" id="'+"field_btn_"+count+'"> <i class="layui-icon">&#xe67e;</i></button></div></div>'
                $('form').append(html);
                form.render();
                $('#field_btn_'+count).on('click', function(){
                    this.parentElement.parentElement.outerHTML="";
                });
                ++count;
                break;
            case 'del':
                $('form').html("\n")
            //     // delHtml()
            //     $('.code-show').text('')
                return false
            case 'saveTable':
                var formName = document.getElementById("formName").value;
                var formDescription = $("#formDescription").value;
                if (!formName) {
                    layer.msg("表单名不能为空");
                    console.log("formName", formName);
                    return false;
                }
                var ele = $('form')[0].children;
                console.log("ele",ele);
                if (!ele.length) return false;
                html = '';
                fields=[];
                var e;
                for (var i=0;i<ele.length;++i){
                    html += ele[i].firstElementChild.firstElementChild.outerHTML;
                    e = ele[i].firstElementChild.firstElementChild.getElementsByTagName('label')
                    if (e.length) {
                        // fields.push(e[0].innerText);
                        fields.push([e[0].innerText,e[0].getAttribute("data-type")]);
                    }
                }
                // console.log("fields", fields);
                // html = '<form class="layui-form" action="" >\n' +html+ '</form>\n\n';
                data = {title:formName, description:formDescription?formDescription:"", body_content:html,js_code:jscode(),dbs_fields:JSON.stringify(fields)};
                axios.post('/form/createForm', data)
                .then(function (response) {
                    // console.log(response);
                    
                    layer.msg("表单创建成功!",{icon:1})
                    var cur =  $(".layui-laypage-skip").find("input").val(); 
                    var limit = $(".layui-laypage-limits").find("option:selected").val();
                    parent.layui.table.reload('formTableId',{
                        url:"/form/formData",
                        // type:"post",
                        where: {
                            page:cur,
                            limit:limit
                        }
                        ,page: {
                            curr: cur //重新从第 1 页开始
                        }
                    });
                    $('form').html("\n")
                    var iframeIndex = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(iframeIndex);
                }).catch(function (error) {
                    layer.msg("表单创建失败!",{icon:2})
                }); 			

                console.log("form_html", html);
                break;
            default:
                layer.msg('类型错误',{icon:2})
        }

        // setHtml(html)
    })



});  